package config

import (
	"fmt"
	"github.com/spf13/viper"
)

type HttpConfig struct {
	Enabled        bool
	Addr           string
	Port           int
	Username       string
	Password       string
	SessionTimeout int
	SecretKey      string
}
type S3Config struct {
	AccessKeyId     string
	SecretAccessKey string
	Region          string
	BucketName      string
}

type OssConfig struct {
	AccessKeyId     string
	SecretAccessKey string
	Endpoint        string
	BucketName      string
}

type SyncConfig struct {
	Paths []struct {
		Local  string
		Remote string
	}
	Interval int
	Excludes []string
}

type DbConfig struct {
	Driver     string
	DataSource string
}

type Config struct {
	Syncer string     // 同步类型
	Http   HttpConfig // 网站服务配置
	S3     S3Config   // aws s3 配置
	Oss    OssConfig  // alibaba cloud oss 配置
	Sync   SyncConfig // 同步配置
	Db     DbConfig   // 数据库配置
}

func BuildConfig() *Config {
	var cfg Config
	//服务提供者
	cfg.Syncer = viper.GetString("syncer")
	//Http 相关配置
	cfg.Http.Enabled = viper.GetBool("http.enabled")
	cfg.Http.Addr = viper.GetString("http.addr")
	cfg.Http.Port = viper.GetInt("http.port")
	cfg.Http.Username = viper.GetString("http.username")
	cfg.Http.Password = viper.GetString("http.password")
	cfg.Http.SessionTimeout = viper.GetInt("http.sessionTimeout")
	cfg.Http.SecretKey = viper.GetString("http.secretKey")
	//S3配置
	cfg.S3.AccessKeyId = viper.GetString("s3.accessKeyId")
	cfg.S3.SecretAccessKey = viper.GetString("s3.secretAccessKey")
	cfg.S3.Region = viper.GetString("s3.region")
	cfg.S3.BucketName = viper.GetString("s3.bucketName")
	//OSS配置
	cfg.Oss.AccessKeyId = viper.GetString("oss.accessKeyId")
	cfg.Oss.SecretAccessKey = viper.GetString("oss.secretAccessKey")
	cfg.Oss.Endpoint = viper.GetString("oss.endpoint")
	cfg.Oss.BucketName = viper.GetString("oss.bucketName")
	//路径配置
	cfg.Sync.Excludes = viper.GetStringSlice("sync.excludes")
	cfg.Sync.Interval = viper.GetInt("sync.interval")
	viper.GetStringMapStringSlice("sync.paths")
	syncPaths := viper.Get("sync.paths").([]interface{})
	for _, syncPath := range syncPaths {
		p := syncPath.(map[string]interface{})
		cfg.Sync.Paths = append(cfg.Sync.Paths, struct {
			Local  string
			Remote string
		}{Local: fmt.Sprintf("%s", p["local"]), Remote: fmt.Sprintf("%s", p["remote"])})
	}
	cfg.Db.Driver = viper.GetString("db.driver") //数据库相关配置
	cfg.Db.DataSource = viper.GetString("db.dataSource")
	return &cfg
}
